<template>


  <div class="container">
    <!-- 科室管理部分 -->
    <div class="title">
      科室 管理
    </div>
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
          v-model="name"
          placeholder="请输入需要查询的科室名称"
          class="search-input"
          clearable
          @keyup.enter="paging(1)">
      </el-input>
      <el-button type="primary" @click="paging(1)">查询</el-button>
      <el-button type="success" @click="openAddDialog">添加科室</el-button>
    </div>

    <!-- 科室表格 -->
    <el-table :data="page.list" style="width: 100%" border>
      <el-table-column prop="id" label="序号" width="100" align="center"></el-table-column>
      <el-table-column prop="name" label="科室名称" width="150" align="center"></el-table-column>
      <el-table-column prop="hospital.name" label="所属医院名称" width="120" align="center" v-if="showHidColumn"></el-table-column>
      <el-table-column prop="ispoint" label="是否重点科室" align="center" width="120">
        <template #default="scope">
          {{ scope.row.ispoint === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template #default="scope">
          <el-button
              v-permission="'user:edit'"
              size="small"
              type="primary"
              @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button
              v-permission="'user:delete'"
              size="small"
              type="danger"
              @click="handleDeleteUser(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 科室分页控件 -->
    <div class="pagination-area">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="paging"
          :current-page="page.pageNum"
          :page-sizes="[2, 3, 4, 5]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
      </el-pagination>
    </div>

    <!-- 科室删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="30%"
        center>
      <span>确定要删除科室 <strong>{{ deleteUser?.name }}</strong> 吗？此操作不可撤销！</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </template>
    </el-dialog>

    <!-- 科室编辑对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        :title="`编辑科室 - ${editUser?.name || ''}`"
        width="500px"
        center>
      <el-form :model="editUser" label-width="80px">
        <el-form-item label="科室名称">
          <el-input v-model="editUser.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="重点科室">
          <el-select v-model="editUser.ispoint" placeholder="请选择">
            <el-option label="否" value="0" />
            <el-option label="是" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属医院" prop="hid">
          <el-select v-model="editUser.hid" placeholder="请选择">
            <el-option v-for="item in HidList" :key="item.id"  :label="item.name" :value="item.id" >{{item.name}}</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 科室添加对话框 -->
    <el-dialog
        v-model="addDialogVisible"
        title="添加科室"
        width="500px"
        center>
      <el-form :model="newAdmin" label-width="80px" :rules="addRules" ref="addForm">
        <el-form-item label="科室名称" prop="name">
          <el-input v-model="newAdmin.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="重点科室" prop="permission">
          <el-select v-model="newAdmin.ispoint" placeholder="请选择">
            <el-option label="是" value="0" />
            <el-option label="否" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属医院" prop="hid">
          <el-select v-model="newAdmin.hid" placeholder="请选择">
            <el-option v-for="item in HidList" :key="item.id"  :label="item.name" :value="item.id" >{{item.name}}</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAdd">保存</el-button>
      </template>
    </el-dialog>

    <!-- 诊所管理部分 -->
    <div class="title">
      诊所 管理
    </div>
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
          v-model="clinicName"
          placeholder="请输入需要查询的诊所名称"
          class="search-input"
          clearable
          @keyup.enter="pagingClinic(1)">
      </el-input>
      <el-button type="primary" @click="pagingClinic(1)">查询</el-button>
      <el-button type="success" @click="openAddClinicDialog">添加诊所</el-button>
    </div>

    <!-- 诊所表格 -->
    <el-table :data="clinicPage.list" style="width: 100%" border>
      <el-table-column prop="id" label="序号" width="100" align="center"></el-table-column>
      <el-table-column prop="name" label="诊所名称" width="150" align="center"></el-table-column>
      <el-table-column prop="hospital.name" label="医院名称" width="150" align="center"></el-table-column>
      <el-table-column prop="department.name" label="所属科室" width="150" align="center"></el-table-column>
      <el-table-column prop="specializedGroup.name" label="所属专科大组" width="150" align="center"></el-table-column>
      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="handleEditClinic(scope.row)">
            修改
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDeleteClinic(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 诊所分页控件 -->
    <div class="pagination-area">
      <el-pagination
          @size-change="handleClinicSizeChange"
          @current-change="pagingClinic"
          :current-page="clinicPage.pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="clinicPage.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="clinicPage.total">
      </el-pagination>
    </div>

    <!-- 诊所编辑对话框 -->
    <el-dialog
        v-model="editClinicDialogVisible"
        :title="`编辑诊所 - ${editClinic?.name || ''}`"
        width="500px"
        center>
      <el-form :model="editClinic" label-width="100px">
        <el-form-item label="诊所名称">
          <el-input v-model="editClinic.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="医院名称" prop="hospitalId">
          <el-select v-model="editClinic.hospitalId" placeholder="请选择医院">
            <el-option
                v-for="item in hospitalList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属科室" prop="departmentId">
          <el-select v-model="editClinic.departmentId" placeholder="请选择科室">
            <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专科大组" prop="specializedGroupId">
          <el-select v-model="editClinic.specializedGroupId" placeholder="请选择专科大组">
            <el-option
                v-for="item in specializedGroupList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editClinicDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveClinicEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 删除诊所确认对话框 -->
    <el-dialog
        v-model="deleteClinicDialogVisible"
        title="确认删除诊所"
        width="30%"
        center>
      <span>确定要删除诊所 <strong>{{ deleteClinic?.name }}</strong> 吗？此操作不可撤销！</span>
      <template #footer>
        <el-button @click="deleteClinicDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDeleteClinic">确定删除</el-button>
      </template>
    </el-dialog>


    <!-- 在template中添加诊所添加对话框 -->
    <el-dialog
        v-model="addClinicDialogVisible"
        title="添加诊所"
        width="500px"
        center>
      <el-form :model="newClinic" label-width="100px" :rules="addClinicRules" ref="addClinicForm">
        <el-form-item label="诊所名称" prop="name">
          <el-input v-model="newClinic.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalId">
          <el-select v-model="newClinic.hospitalId" placeholder="请选择医院" @change="handleHospitalChange">
            <el-option
                v-for="item in hospitalList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属科室" prop="departmentId">
          <el-select v-model="newClinic.departmentId" placeholder="请选择科室">
            <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专科大组" prop="specializedGroupId">
          <el-select v-model="newClinic.specializedGroupId" placeholder="请选择专科大组">
            <el-option
                v-for="item in specializedGroupList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addClinicDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveClinicAdd">保存</el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";

// 科室管理相关代码
const page = ref({
  pageNum: 1,
  pageSize: 5,
  total: 0,
  list: []
});
const name = ref("");
const newAdmin = ref({
  name: '',
  password: '',
  permission: '',
  hid: null
});

// 加载科室数据
const paging = async (curPage = 1) => {
  page.value.pageNum = curPage;
  const res = await axios.get('/h_department/selAll', {
    params: {
      curPage: page.value.pageNum,
      pageSize: page.value.pageSize,
      name: name.value
    }
  });
  page.value = res.data;
};

// 更改每页大小
const handleSizeChange = (newSize) => {
  page.value.pageSize = newSize;
  paging(1);
};

const HidList = ref([])
const getHidList = () => {
  axios.get('/hospital/selAllhospital').then(res => {
    HidList.value = res.data.data
  })
}

// 是否显示 hid 列
const showHidColumn = ref(true);

// 科室删除相关
const deleteUser = ref(null)
const deleteDialogVisible = ref(false);

const handleDeleteUser = (row) => {
  deleteUser.value = row;
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  if (!deleteUser.value) return;

  try {
    await axios.get(`/h_department/delById?id=${deleteUser.value.id}`);
    ElMessage.success('删除成功');

    // 智能分页处理
    if (page.value.list.length === 1 && page.value.pageNum > 1) {
      paging(page.value.pageNum - 1);
    } else {
      paging(page.value.pageNum);
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message));
  } finally {
    deleteDialogVisible.value = false;
  }
};

// 科室编辑相关
const editDialogVisible = ref(false);
const editUser = ref({
  id: null,
  name: '',
  ispoint: null,
  hid: null
});

const handleEdit = (row) => {
  editUser.value = { ...row };
  editDialogVisible.value = true;
};

const saveEdit = async () => {
  if (!editUser.value.id) return;
  try {
    const params = new URLSearchParams({
      id: editUser.value.id,
      name: editUser.value.name,
      ispoint: editUser.value.ispoint || '',
      hid: editUser.value.hid || ''
    }).toString();

    await axios.get(`/h_department/update?${params}`);

    ElMessage.success('修改成功');
    editDialogVisible.value = false;
    paging(page.value.pageNum);

  } catch (error) {
    console.error('更新失败:', error);
    if (error.response) {
      ElMessage.error(`服务器错误:${error.response.status} -${error.response.data?.message || '未知错误'}`);
    } else if (error.request) {
      ElMessage.error('网络错误: 服务器无响应');
    } else {
      ElMessage.error(`请求错误: ${error.message}`);
    }
  }
}

// 科室添加相关
const addDialogVisible = ref(false);
const addRules = ref({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  ispoint: [
    { required: true, message: '请选择权限', trigger: 'change' }
  ]
});

const addForm = ref(null);

const openAddDialog = () => {
  newAdmin.value = {
    id: null,
    name: '',
    hid: null,
    ispoint: null
  };

  if (addForm.value) {
    addForm.value.resetFields();
  }

  addDialogVisible.value = true;
};

const saveAdd = async () => {
  try {
    await addForm.value.validate();

    const params = {
      name: newAdmin.value.name,
      ispoint: newAdmin.value.ispoint,
      hid: newAdmin.value.hid,
    };

    if (newAdmin.value.hid !== null && newAdmin.value.hid !== undefined) {
      params.hid = newAdmin.value.hid;
    }

    const response = await axios.get('/h_department/add', { params });
    console.log(response.data);

    if (response.data === 1) {
      ElMessage.success({
        message: '管理员添加成功',
        duration: 3000,
        showClose: true,
      });
      addDialogVisible.value = false;
      paging(1);
    } else {
      ElMessage.error('添加失败，请重试');
    }
  } catch (error) {
    console.error('添加管理员失败:', error);

    if (error.response) {
      if (error.response.status === 400) {
        ElMessage.error('请求参数错误，请检查输入');
      } else {
        ElMessage.error(`服务器错误: ${error.response.status}`);
      }
    } else if (error.request) {
      ElMessage.error('网络错误: 服务器无响应');
    } else {
      ElMessage.error(`请求错误: ${error.message}`);
    }
  }
};

// 诊所管理相关代码
const clinicPage = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list: []
});
const clinicName = ref("");

// 诊所编辑相关
const editClinicDialogVisible = ref(false);
const editClinic = ref({
  id: null,
  name: '',
  hospitalId: null,
  departmentId: null,
  specializedGroupId: null
});

// 下拉框数据
const hospitalList = ref([]);
const departmentList = ref([]);
const specializedGroupList = ref([]);

// 获取医院列表
const getHospitalList = async () => {
  const res = await axios.get('/hospital/selAllhospital');
  hospitalList.value = res.data.data;
};

// 获取科室列表
const getDepartmentList = async () => {
  const res = await axios.get('/department/selAllDepartment');
  departmentList.value = res.data.data;
};

// 获取专科大组列表
const getSpecializedGroupList = async () => {
  const res = await axios.get('/specialized_group/selAllspecialgroup');
  specializedGroupList.value = res.data.data;
};

// 处理编辑诊所
const handleEditClinic = (row) => {
  console.log(row)
  editClinic.value = {
    id: row.id,
    name: row.name,
    hospitalId: row.hid,      // 映射到hospitalId
    departmentId: row.did,     // 映射到departmentId
    specializedGroupId: row.sgId // 映射到specializedGroupId
  };

  console.log(editClinic.value.hospitalId)
  console.log(editClinic.value.departmentId)
  editClinicDialogVisible.value = true;
};

// 保存诊所修改
const saveClinicEdit = async () => {
  if (!editClinic.value.id) {
    ElMessage.error('诊所ID不能为空');
    return;
  }

  try {
    // 构建请求参数，确保字段名与后端一致
    const params = {
      id: editClinic.value.id,
      name: editClinic.value.name || '',
      h_id: editClinic.value.hospitalId || '',  // 对应数据库的h_id字段
      did: editClinic.value.departmentId || '', // 对应数据库的did字段
      sg_id: editClinic.value.specializedGroupId || '' // 对应数据库的sg_id字段
    };

    console.log(params)

    // 检查必填字段
    if (!params.name) {
      ElMessage.error('诊所名称不能为空');
      return;
    }

    // 使用GET请求，保持与原有代码一致
    const response = await axios.get('/clinic/update', { params });

    if (response.data === 1) {
      ElMessage.success('诊所信息更新成功');
      editClinicDialogVisible.value = false;
      pagingClinic(clinicPage.value.pageNum);
    } else {
      ElMessage.error('更新失败，请重试');
    }

  } catch (error) {
    console.error('更新诊所失败:', error);
    if (error.response) {
      if (error.response.status === 400) {
        ElMessage.error('请求参数错误: ' + (error.response.data?.message || '请检查输入数据'));
      } else {
        ElMessage.error(`服务器错误: ${error.response.status}`);
      }
    } else if (error.request) {
      ElMessage.error('网络错误: 服务器无响应');
    } else {
      ElMessage.error(`请求错误: ${error.message}`);
    }
  }
};

// 诊所删除相关
const deleteClinic = ref(null);
const deleteClinicDialogVisible = ref(false);

// 加载诊所数据
const pagingClinic = async (curPage = 1) => {
  clinicPage.value.pageNum = curPage;
  const res = await axios.get('/clinic/selAllname', {
    params: {
      curPage: clinicPage.value.pageNum,
      pageSize: clinicPage.value.pageSize,
      name: clinicName.value
    }
  });
  clinicPage.value = res.data;
};

// 更改每页大小
const handleClinicSizeChange = (newSize) => {
  clinicPage.value.pageSize = newSize;
  pagingClinic(1);
};

// 处理删除诊所
const handleDeleteClinic = (row) => {
  deleteClinic.value = row;
  deleteClinicDialogVisible.value = true;
};

// 确认删除诊所
const confirmDeleteClinic = async () => {
  if (!deleteClinic.value) return;

  try {
    await axios.get(`/clinic/delById?id=${deleteClinic.value.id}`);
    ElMessage.success('诊所删除成功');

    // 智能分页处理
    if (clinicPage.value.list.length === 1 && clinicPage.value.pageNum > 1) {
      pagingClinic(clinicPage.value.pageNum - 1);
    } else {
      pagingClinic(clinicPage.value.pageNum);
    }
  } catch (error) {
    console.error('删除诊所失败:', error);
    ElMessage.error('删除诊所失败: ' + (error.response?.data?.message || error.message));
  } finally {
    deleteClinicDialogVisible.value = false;
  }
};

// 初始化加载
onMounted(() => {
  paging();
  pagingClinic();
  getHidList();
  getHospitalList();
  getDepartmentList();
  getSpecializedGroupList();
});



// 在script中添加以下代码
// 诊所添加相关
const addClinicDialogVisible = ref(false);
const addClinicForm = ref(null);
const newClinic = ref({
  name: '',
  hospitalId: null,
  departmentId: null,
  specializedGroupId: null
});

// 添加诊所表单验证规则
const addClinicRules = ref({
  name: [
    { required: true, message: '请输入诊所名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  hospitalId: [
    { required: true, message: '请选择所属医院', trigger: 'change' }
  ],
  departmentId: [
    { required: true, message: '请选择所属科室', trigger: 'change' }
  ],
  specializedGroupId: [
    { required: true, message: '请选择专科大组', trigger: 'change' }
  ]
});

// 打开添加诊所对话框
const openAddClinicDialog = () => {
  newClinic.value = {
    name: '',
    hospitalId: null,
    departmentId: null,
    specializedGroupId: null
  };

  if (addClinicForm.value) {
    addClinicForm.value.resetFields();
  }

  addClinicDialogVisible.value = true;
};

// 保存添加的诊所
const saveClinicAdd = async () => {
  try {
    // 验证表单
    await addClinicForm.value.validate();

    // 构建请求参数，与后端接口保持一致
    const params = {
      name: newClinic.value.name,
      h_id: newClinic.value.hospitalId,
      did: newClinic.value.departmentId,
      sg_id: newClinic.value.specializedGroupId
    };

    // 调用后端接口
    const response = await axios.get('/clinic/add', { params });

    if (response.data === 1) {
      ElMessage.success('诊所添加成功');
      addClinicDialogVisible.value = false;
      pagingClinic(clinicPage.value.pageNum);
    } else {
      ElMessage.error('添加失败，请重试');
    }
  } catch (error) {
    console.error('添加诊所失败:', error);
    if (error.response) {
      if (error.response.status === 400) {
        ElMessage.error('请求参数错误: ' + (error.response.data?.message || '请检查输入数据'));
      } else {
        ElMessage.error(`服务器错误: ${error.response.status}`);
      }
    } else if (error.request) {
      ElMessage.error('网络错误: 服务器无响应');
    } else {
      if (error.message !== 'Validate Failed') {
        ElMessage.error(`请求错误: ${error.message}`);
      }
    }
  }
};

// 医院选择变化时，可以添加相关逻辑
const handleHospitalChange = (hospitalId) => {
  // 如果需要根据医院筛选科室，可以在这里实现
  // 例如: filterDepartmentsByHospital(hospitalId);
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 18px;
  font-weight: bold;
  margin: 20px 0 15px 0;
  color: #333;
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>